﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using COMOSOFT.Class;
using COMOSOFT.Main;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using System.IO;
using DevExpress.XtraEditors.Repository;
using DevExpress.Xpf;

namespace COMOSOFT.MatarialManagement.Forms
{
    public partial class FrmMALibrary : Form
    {        
        ClassShare cls = new ClassShare("FrmMALabriry");        
        int MAID,MADID;
        DataTable dbTemp = null;
        bool IsType=false, IsArt=false,IsCom=false;
        Image img;
        int numrow;
        string type=null, art=null, com=null;
        string path1 = null;
        string path2 = null;        
        public FrmMALibrary(int _MAID)
        {   
            InitializeComponent();
            this.MAID = _MAID;
            ClassShare.frMALib = this;
            if (MAID == -1)
            {
                mASourceTableAdapter.Fill(dataSetMatarial.MASource, MAID);
                groupControl_Details.Enabled = false;
            }
            cls.LoadLayout(gridView_MALibraryDetails,ClassShare.lcMaterial+@"\LayOutMADetails.XML");
        }
      
        #region [LoadData]
        public void LoadData()
        {
            try
            {               
                employeeTableAdapter.Fill(dataSetOrderManagement.Employee);
                customsCodeTableAdapter.Fill(dataSetMatarial.CustomsCode);
                supplierTableAdapter.Fill(dataSetMatarial.Supplier);
                if (MAID > 0)
                {                    
                    mASourceTableAdapter.Fill(dataSetMatarial.MASource, MAID);
                    mASourceDetailsTableAdapter.Fill(dataSetMatarial.MASourceDetails, MAID);
                    this.Text = "Item: " + txt_Article.Text + "-" + txt_Art.Text;                   
                    //Load Image                   
                    dbTemp = new DataTable();
                    dbTemp.Columns.Add("ID");
                    dbTemp.Columns.Add("Img1", typeof(object));
                    dbTemp.Columns.Add("Img2", typeof(object));
                    DataTable dbMA = dataSetMatarial.MASourceDetails;
                    numrow = dbMA.Rows.Count;
                    if (dbMA.Rows.Count > 0)
                    {
                        for (int i = 0; i < dbMA.Rows.Count; i++)
                        {
                            
                            DataRow newrow = dbTemp.NewRow();
                            if (dbMA.Rows[i]["Picture1"].ToString() != "")
                            {
                                //dowloadfile
                                if (!File.Exists(ClassShare.lcMaterial+dbMA.Rows[i]["Picture1"].ToString()))
                                   cls.Dowload(ClassShare.ftpMaterial, ClassShare.lcMaterial, dbMA.Rows[i]["Picture1"].ToString());
                                string path1 = ClassShare.lcMaterial + dbMA.Rows[i]["Picture1"].ToString();
                                byte[] img = System.IO.File.ReadAllBytes(path1);
                                newrow["Img1"] = img;
                            }                                                 
                            else
                            {
                                if (!File.Exists(ClassShare.lcMaterial + "noImage.gif"))
                                   cls.Dowload(ClassShare.ftpMaterial, ClassShare.lcMaterial, "noImage.gif");
                                string path = ClassShare.lcMaterial + "noImage.gif";
                                byte[] NoImg = System.IO.File.ReadAllBytes(path);
                                newrow["Img1"] = NoImg;
                            }

                            if (dbMA.Rows[i]["Picture2"].ToString() != "")
                            {
                                if (!File.Exists(ClassShare.lcMaterial + dbMA.Rows[i]["Picture2"].ToString()))
                                   cls.Dowload(ClassShare.ftpMaterial, ClassShare.lcMaterial, dbMA.Rows[i]["Picture2"].ToString());
                                string path2 = ClassShare.lcMaterial + dbMA.Rows[i]["Picture2"].ToString();
                                byte[] img = System.IO.File.ReadAllBytes(path2);
                                newrow["Img2"] = img;
                            }
                            else
                            {
                                if (!File.Exists(ClassShare.lcMaterial + "noImage.gif"))
                                   cls.Dowload(ClassShare.ftpMaterial, ClassShare.lcMaterial, "noImage.gif");
                                string path = ClassShare.lcMaterial + "noImage.gif";
                                byte[] NoImg = System.IO.File.ReadAllBytes(path);
                                newrow["Img2"] = NoImg;
                            }
                            newrow["ID"] = dbMA.Rows[i]["MADID"];
                            dbTemp.Rows.Add(newrow);
                        }
                    }                    
                    //--------------------------
                    
                }
            }
            catch
            {
                MessageBox.Show("Disconnect database! Please try again!", "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region [Show Image]
        private Image LoadImg(string ID, int row,string flag)
        {
            try
            {
                if (dbTemp.Rows.Count > row && dbTemp.Rows[row]["ID"].ToString() == ID)
                {                 
                  using (System.IO.MemoryStream str = new System.IO.MemoryStream(dbTemp.Rows[row]["Img" + flag] as byte[]))
                    {
                        img = Image.FromStream(str);
                        return img;
                    }
                }
            }
            catch
            {
               // MessageBox.Show(ex.Message);
            }
            return img;
        }          
        // Show Image
        private void gridView_MALibraryDetails_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                DataRowView row = e.Row as DataRowView;
                GridView view = sender as GridView;
                if (!view.IsNewItemRow(e.ListSourceRowIndex) && numrow > e.ListSourceRowIndex)
                {
                    if (e.Column.FieldName == "Pictureone" && e.IsGetData)
                        e.Value = LoadImg(row["MADID"].ToString(), e.ListSourceRowIndex, "1");
                    if (e.Column.FieldName == "Picturetwo" && e.IsGetData)
                        e.Value = LoadImg(row["MADID"].ToString().ToString(), e.ListSourceRowIndex, "2");
                }
            }
            catch
            {
                //MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #endregion

        #region [Upadte Master]
        public void AddNew()
        {
            mASourceBindingSource.AddNew();            
            txt_Distribute.EditValue = "Fabric";
            txt_CreateDate.EditValue = DateTime.Now.ToShortDateString();
            txt_CreateBy.EditValue = Convert.ToInt64(ClassShare.Usid);
        }
        public void UpdateMAL()
        {
            try
            {
                if (MAID == -1)
                {
                    //Insert
                    mASourceBindingSource.EndEdit();
                    mASourceTableAdapter.Update(dataSetMatarial.MASource);
                    dataSetMatarial.MASource.AcceptChanges();
                    MAID = Convert.ToInt32(txt_MAID.Text);
                    if (groupControl_Details.Enabled == false)
                    {
                        groupControl_Details.Enabled = true;
                        this.Text = "Item: " + txt_Article.Text + "-" + txt_Art.Text;
                    }
                }
                else
                {
                    //update
                    if (ClassShare.Usid == Convert.ToInt32(txt_CreateBy.EditValue))
                    {
                        mASourceBindingSource.EndEdit();
                        mASourceTableAdapter.Update(dataSetMatarial.MASource);
                        dataSetMatarial.MASource.AcceptChanges();                        
                    }
                    else
                    { 
                        MessageBox.Show("You don't permission!", "Can't update....", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                //MessageBox.Show("Update Successfully!", "Finishing....", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }
        public void DeleteMALib()
        {
            try
            {
                if (ClassShare.Usid == Convert.ToInt32(txt_CreateBy.EditValue))
                {
                    if (MessageBox.Show("Are you sure you want to delete?", "Delete item", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        dataSetMatarial.MASource.Rows[0].Delete();
                        mASourceTableAdapter.Update(dataSetMatarial.MASource);
                        dataSetMatarial.MASource.AcceptChanges();
                        this.Close();
                    }
                }
                else
                {
                    MessageBox.Show("You don't permission!", "Can't update....", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                MessageBox.Show("Can't delete object! Have a object using it!", "Warning....", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #endregion

        #region [Update Details]
        private void gridView_MALibraryDetails_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {                
                GridView view =sender as GridView;               
                if (view.IsNewItemRow(view.FocusedRowHandle))
                {
                    mASourceDetailsBindingSource.EndEdit();
                    mASourceDetailsTableAdapter.Update(dataSetMatarial.MASourceDetails);                    
                    dataSetMatarial.MASourceDetails.AcceptChanges();
                    int index=dataSetMatarial.MASourceDetails.Rows.Count;
                    MADID = Convert.ToInt32(dataSetMatarial.MASourceDetails[index-1]["MADID"]);                  

                    cls.UpdateData("sp_MASDetailsUpdate", new string[3] { "@MADID", "@img1", "@img2" }, new object[3] { MADID, path1, path2 });
                }
                else
                {
                    int USID = Convert.ToInt32(view.GetFocusedDataRow()["CreateBy"]);
                    if (ClassShare.Usid == USID)
                    {
                        mASourceDetailsBindingSource.EndEdit();
                        mASourceDetailsTableAdapter.Update(dataSetMatarial.MASourceDetails);                       
                        dataSetMatarial.MASourceDetails.AcceptChanges();
                        MADID = Convert.ToInt32(view.GetFocusedDataRow()["MADID"]);

                        cls.UpdateData("sp_MASDetailsUpdate", new string[3] { "@MADID", "@img1", "@img2" }, new object[3] { MADID, path1, path2 });
                    }
                    else
                    {
                        MessageBox.Show("You don't permission!", "Can't update....", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                LoadData();                
            }
            catch
            {
              MessageBox.Show("Not thing Update!", "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                 GridView view =gridView_MALibraryDetails as GridView;
                 int USID = Convert.ToInt32(view.GetFocusedDataRow()["CreateBy"]);
                if (ClassShare.Usid == USID)
                {
                    if (MessageBox.Show("Are you sure you want to delete?", "Delete item", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        int MADID = Convert.ToInt32(gridView_MALibraryDetails.GetFocusedDataRow()["MADID"]);
                        cls.UpdateData("sp_MADetailsDelete", new string[1] { "@MADID" }, new object[1] { MADID });
                        mASourceDetailsTableAdapter.Fill(dataSetMatarial.MASourceDetails, MAID);
                    }
                }
                else
                {
                    MessageBox.Show("You don't permission!", "Can't update....", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                MessageBox.Show("Can't delete this object! Because it using in MAListDetails!!", "Delete Fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }    
        #endregion

        private void gridView_MALibraryDetails_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            gridView_MALibraryDetails.SetFocusedRowCellValue("MAID", MAID);
            gridView_MALibraryDetails.SetFocusedRowCellValue("CreateBy", ClassShare.Usid);
            gridView_MALibraryDetails.SetFocusedRowCellValue("PriceDate", DateTime.Now.ToShortDateString());
        }
        // Update Supplier
        #region [Add Supplier]
        private void repositoryItemGridLookUpEdit_supplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "Add")
                {
                    supplierContactTableAdapter.Fill(dataSetMatarial.SupplierContact, -1);
                    supplierBindingSource.AddNew();
                    gridView_NewSupplier.SetFocusedRowCellValue("MASUPID", txt_ID.Text);                    
                    dockPanel_Supplier.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - dockPanel_Supplier.Width, Screen.PrimaryScreen.WorkingArea.Height / 2 - dockPanel_Supplier.Height);
                    groupControl_SupDetails.Enabled = false;
                    dockPanel_Supplier.Show();                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }       
        #endregion

        private void FrmMALibrary_Load(object sender, EventArgs e)
        {            
            this.sp_MAGetCompositionTableAdapter.Fill(this.dataSetMatarial.sp_MAGetComposition,"Fabric");
            this.sp_MAGetTypeTableAdapter.Fill(this.dataSetMatarial.sp_MAGetType,"Fabric");
            dockPanel_Supplier.Hide();
            dockPanel_AddItem.Hide();
        }

        #region [Upadate Supplier Details]
        private void gridView_NewSupplier_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                supplierContactBindingSource.EndEdit();
                supplierContactTableAdapter.Update(dataSetMatarial.SupplierContact);
                dataSetMatarial.SupplierContact.AcceptChanges();
                supplierTableAdapter.Fill(dataSetMatarial.Supplier);
            }
            catch
            {
                MessageBox.Show("Not thing update!", "Update Fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Choose Image]
        private void repositoryItemImageEdit_Picture_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                GridView view = gridView_MALibraryDetails as GridView;
                if (e.Button.Tag.ToString() != "0")
                {
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.InitialDirectory = @"C:\";
                    dlg.Filter = "All file (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
                    dlg.Title = "Please select an image file to encrypt.";
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        string name = Path.GetFileName(dlg.FileName);
                        cls.UploadFile(dlg.FileName, ClassShare.ftpMaterial);  
                        if (e.Button.Tag.ToString() == "1")
                        {                        
                             path1 = name;
                             byte[] img = System.IO.File.ReadAllBytes(dlg.FileName);
                             MemoryStream str = new MemoryStream(img);
                             System.Drawing.Image image = System.Drawing.Image.FromStream(str);
                             view.SetFocusedRowCellValue("Pictureone", image);
                        }
                        else
                        {                         
                            path2 = name;
                        }
                        string Remark = view.GetFocusedDataRow()["Remark"].ToString()+" ";
                        view.SetFocusedRowCellValue("Remark",Remark);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
   
        private void bnt_Okay_Click(object sender, EventArgs e)
        {
            try
            {
                if ((Convert.IsDBNull(txt_Type.EditValue) ? "" : txt_Type.EditValue.ToString()) != "")
                    type = txt_Type.EditValue.ToString();
                if ((Convert.IsDBNull(txt_Article.EditValue) ? "" : txt_Article.EditValue.ToString()) != "")               
                    art = txt_Article.EditValue.ToString();
                if ((Convert.IsDBNull(txt_composition.EditValue) ? "" : txt_composition.EditValue.ToString()) != "")               
                    com = txt_composition.EditValue.ToString();
                if (IsType == true)
                    type = txt_Add.EditValue.ToString();
                else
                {
                    if (IsArt == true)
                        art = txt_Add.EditValue.ToString();
                    else
                        com = txt_Add.EditValue.ToString();
                }
                if (MAID < 0)
                {
                    DataTable dtb = cls.GetData("sp_MAAddItem", new string[] { "@MAID", "@Type", "@Article", "@Composition", "@CreateDate", "@CreateBy", "@Distribute", "@Flag" }, new object[] { 1, type, art, com, Convert.ToDateTime(txt_CreateDate.EditValue), txt_CreateBy.EditValue,"Fabric", 1 });
                    MAID = Convert.ToInt32(dtb.Rows[0]["ID"]);
                }
                else
                {
                    cls.GetData("sp_MAAddItem", new string[] { "@MAID", "@Type", "@Article", "@Composition", "@CreateDate", "@CreateBy", "@Distribute", "@Flag" }, new object[] { MAID, type, art, com, Convert.ToDateTime(txt_CreateDate.EditValue), txt_CreateBy.EditValue,"Fabric", 0 });
                } 
                dockPanel_AddItem.Close();
                if (IsType == true)
                    sp_MAGetTypeTableAdapter.Fill(dataSetMatarial.sp_MAGetType,"Fabric");
                else
                {
                    if (IsArt == true)
                        sp_MAGetArticleTableAdapter.Fill(dataSetMatarial.sp_MAGetArticle, txt_Type.EditValue.ToString());
                    else
                        sp_MAGetCompositionTableAdapter.Fill(dataSetMatarial.sp_MAGetComposition,"Fabric");
                }
                IsType = false;
                IsArt = false;
                txt_Add.Text = "";
                LoadData();
            }
            catch
            { 
            }
        }

        private void dataNavigator_bnt_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (e.Button.Tag.ToString() == "Save")
            {
                string Name, Nick, Address, Phone, Fax, Email, Website, Remark;
                Name = txt_Fullname.Text;
                Nick = txt_NickName.Text;
                Address = txt_Address.Text;
                Phone = txt_Phone.Text;
                Fax = txt_Fax.Text;
                Email = txt_Email.Text;
                Website = txt_website.Text;
                Remark = txt_Remark.Text;
                int kq = cls.UpdateData("sp_SupplierInsert", new string[] { "@NickName", "@FullName", "@Address", "@Phone", "@Fax", "@Email", "@Website", "@Remark" }, new object[] { Nick, Name, Address, Phone, Fax, Email, Website, Remark });
                if (groupControl_SupDetails.Enabled == false)
                    groupControl_SupDetails.Enabled = true;
                dataNavigator_bnt.Buttons.CustomButtons[0].Enabled = false;
            }
            else
            {
                dockPanel_Supplier.Close();
                txt_Fullname.Text = "";
                txt_NickName.Text = "";
                txt_Address.Text = "";
                txt_Phone.Text = "";
                txt_Fax.Text = "";
                txt_Email.Text = "";
                txt_website.Text = "";
                txt_Remark.Text = "";
            }
            supplierTableAdapter.Fill(dataSetMatarial.Supplier);
        }

        #region [CustomCode]
        private void dataNavigator_CustomCode_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "Save")
                {
                    customsCodeBindingSource.EndEdit();
                    customsCodeTableAdapter.Update(dataSetMatarial.CustomsCode);
                    dataSetMatarial.CustomsCode.AcceptChanges();
                    dataNavigator_CustomCode.Buttons.CustomButtons[0].Enabled = true;
                }
                else if (e.Button.Tag.ToString() == "New")
                {
                    customsCodeBindingSource.AddNew();
                    txtCreateBy.EditValue = Convert.ToInt64(ClassShare.Usid);
                    txtCreateDate.EditValue = DateTime.Now;
                    dataNavigator_CustomCode.Buttons.CustomButtons[0].Enabled = false;
                }
                else
                    dockPanel_HSCode.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txt_CusCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString() == "Add")
            {               
                dockPanel_HSCode.Show();
            }
        }
        #endregion

        private void txt_Type_EditValueChanged(object sender, EventArgs e)
        {
            sp_MAGetArticleTableAdapter.Fill(dataSetMatarial.sp_MAGetArticle, txt_Type.EditValue.ToString());
        }

        private void AddItem_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString() != "0")
            {
                switch (e.Button.Tag.ToString())
                {
                    case "AddType":
                        IsType = true;
                        break;
                    case "AddArt":
                        IsArt = true;
                        break;
                    case "AddCom":
                        IsCom = true;
                        break;
                }
                dockPanel_AddItem.Show();
            }            
        }

        private void bnt_Cancel_Click(object sender, EventArgs e)
        {
            dockPanel_AddItem.Close();
            txt_Add.Text = "";
        }

        private void saveLayoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cls.SaveLayout(gridView_MALibraryDetails,ClassShare.lcMaterial+@"\LayOutMADetails.XML");
        }

        public void EnableGridDetails()
        {            
            if (groupControl_Details.Enabled == false)
            {
                groupControl_Details.Enabled = true;               
                this.Text = "Item: " + txt_Article.Text + "-" + txt_Art.Text;
            }
        }

        public void ShowButton()
        {
            dataNavigator_AddMA.Visible = true;
        }

        #region[EventDataNavigator]
        private void dataNavigator_AddMA_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.Tag.ToString())
            {
                case "Save":
                    UpdateMAL();
                    RefreshGaneralView();
                    break;
                case "Refresh":
                    LoadData();
                    break;
                case "Delete":
                    DeleteMALib();
                    RefreshGaneralView();
                    break;
            }
        }
        #endregion

        #region[Copy/Paste]
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_MALibraryDetails as GridView;
                int[] rowHandles = view.GetSelectedRows();
                int[] destRowHandles = rowHandles;

                for (int j = 0; j < rowHandles.Length; j++)
                {
                    int rowHandle = rowHandles[j];
                    view.AddNewRow();
                    DataRow row = view.GetDataRow(view.FocusedRowHandle);
                    DataRow sourceRow = view.GetDataRow(rowHandle);
                    for (int i = 1; i < row.Table.Columns.Count; i++)
                    {                       
                        row[i] = sourceRow[i];
                    }
                    destRowHandles[j] = view.FocusedRowHandle;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion              

        #region[RefreshGaneralView]
        private void RefreshGaneralView()
        {
            if (ClassShare.frFabricGV != null && !ClassShare.frFabricGV.IsDisposed)
            {
                ClassShare.frFabricGV.LoadMAGV(DateTime.Now.Year, "Fabric");
            }
        }
        #endregion
    }
}
